package cn.monkey.io.transport.netty.server.codec.protocol.tcp.http;

import cn.monkey.io.transport.netty.server.codec.protocol.tcp.TcpServerProtocolPredicate;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ReferenceCountUtil;


public interface HttpServerProtocolPredicate extends TcpServerProtocolPredicate {

    HttpServerProtocolPredicate INSTANCE = new HttpServerProtocolPredicate() {

    };


    @Override
    default boolean test0(SocketChannel channel, ByteBuf data) {
        ByteBuf byteBuf = Unpooled.copiedBuffer(data);
        try {
            String s = new String(byteBuf.array());
            String[] split = s.split("\n");
            if (split.length == 0) {
                return false;
            }
            String line0 = split[0];
            String[] line0Arr = line0.split(" ");
            if (line0Arr.length != 3) {
                return false;
            }
            try {
                HttpVersion httpVersion = HttpVersion.valueOf(line0Arr[2]);
                return httpVersion != null;
            } catch (IllegalArgumentException ignore) {
                return false;
            }
        } finally {
            ReferenceCountUtil.release(byteBuf);
        }

    }
}
